package com.liruo.treasureattic.common.util;

import cn.hutool.core.codec.Base64;
import com.liruo.treasureattic.common.util.err.ParseException;
import org.apache.commons.lang3.StringUtils;

/**
 * @Author:liruo
 * @Date:2022-12-04-00:51:40
 * @Desc
 */
public class Base64ImageUtil {
    public static class Base64Image{
        public byte[] byteStream;
        public String extension;

        public Base64Image(byte[] byteStream, String extension) {
            this.byteStream = byteStream;
            this.extension = extension;
        }
    }

    /**
     *
     * @param base64Image  _IMAGE_STRING
     * @return
     */
    public static Base64Image base64ToImage(String base64Image){
        if(StringUtils.isBlank(base64Image)){
            return null;
        }
        String[] split = base64Image.split(";");
        String[] imageTypeInfo = split[0].split("/");
        if(!imageTypeInfo[0].equals("data:image")){
            throw new ParseException("no image because base64 prefix=" + imageTypeInfo[0]);
        }
        String imageExtension = imageTypeInfo[1];
        String[] strings = split[1].split(",");
        if(!strings[0].equals("base64")){
            throw new ParseException("unSupport image encode =" + strings[0]);
        }
        String base64Picture = strings[1];
        byte[] decode = Base64.decode(base64Picture);
        //听说是调整异常数据
        for(int i = 0; i < decode.length; i++){
            if(decode[i] < 0){
                decode[i] += 256;
            }
        }
        return new Base64Image(decode,imageExtension);
    }

    /**
     *
     * @param bytes 就是简单的图片的byte
     * @return
     */
    public static String imageToBase64(byte[] bytes){
        return Base64.encode(bytes);
    }
}
